# -*- coding:utf-8 -*-
# 注册流程
# -1- 用户客户端根据本地填写的密码(去空格，重复2次)，+密钥生成一个md5字符窜
# -2- '%s:%s:%u:%u' % (user_name, user_pass, sex, birth_year)
# -3- 使用base64编码
import userDao, base64, time, hashlib
import os
os.sys.path.append('../../utils/constants/')
from constants import *

class userLogic(object):
    "user operation about storage"
    def __init__(self, dbHandler, memcache_conn):
        # 配置
        self.__dao = userDao.userDao(dbHandler)
        self.__register_format = '%s:%s:%u:%u'
        self.__checkin_format = '%s:%s'
        self.__mc_expire_time = 86400*10

        # 活跃度的分值
        # 登录奖励
        self.__bonus_checkin      = 5
        # 顶贴奖励
        self.__bonus_ding         = 1
        # 发贴奖励
        self.__bonus_post_thread  = 10
        # 评论奖励
        self.__bonus_post_comment = 5
        # 发囧事奖励
        self.__bonus_post_jiong   = 20
        # 评五星奖励
        self.__bonus_give_me_five = 100

        # 声望值的分值
        # 发表的帖子被设为精华奖励
        self.__bonus_selected     = 10
        # 发表的帖子/评论/囧事被其他用户顶的奖励
        self.__bonus_dinged       = 2

        self.__mc = memcache_conn

    def register(self, uip, base64_string):
        key = 'regi:%s:%s' % (uip, time.strftime("%Y%m%H"), )
        md5str = hashlib.md5(key).hexdigest()
        mckey = md5str[:16]
        if self.__mc.get(mckey):
            ret = {}
            ret['retcode'] = E_REGISTER_HIGH_FREQUENCY
            ret['message'] = 'ip: %s register too many.' % (uip,)
            return ret

        try:
            string_decode = base64.standard_b64decode(base64_string)
        except:
            ret = {}
            ret['retcode'] = E_REGISTER_BASE64_DECODE_FAIL
            ret['message'] = 'b64decode get exception'
            return ret
        if 3 != string_decode.count(':'):
            ret = {}
            ret['retcode'] = E_REGISTER_BASE64_STRING_INVALID
            ret['message'] = 'string_decode format invalid.'
            return ret
        user_name, user_pass, sex, birth_year = string_decode.split(':')
        user_item = {}
        user_item['user_name'] = user_name
        user_item['user_pass'] = user_pass
        user_item['sex'] = int(sex)
        user_item['birth_year'] = int(birth_year)
        user_item['creat_time'] = int(time.time())
        #print user_item
        ret = self.__dao.add(user_item)
        if 0 == ret['retcode']:
            # 加入memcache，控制一个IP一天内的注册次数
            if not self.__mc.get(mckey):
                self.__mc.add(mckey, user_name, self.__mc_expire_time)
            ret['retbody']['code'] = base64.standard_b64encode('%s:%s' % (user_name, user_pass,))
        return ret

    def check_uname(self, uname):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = 'OK'
        dbret = self.__dao.get_userinfo_by_name(uname)
        if dbret.has_key('user_name'):
            ret['retcode'] = E_REGISTER_ALREADY_EXIST
            ret['message'] = 'user %s already exists.' % uname
        return ret
    def checkin(self, base64_string):
        try:
            string_decode = base64.standard_b64decode(base64_string)
        except:
            ret = {}
            ret['retcode'] = E_CHECKIN_BASE64_DECODE_FAIL
            ret['message'] = 'b64decode get exception'
            return ret
        if 1 != string_decode.count(':'):
            ret = {}
            ret['retcode'] = E_CHECHIN_BASE64_STRING_INVALID
            ret['message'] = 'string_decode format invalid.'
            return ret
        user_name, user_pass = string_decode.split(':')
        ret = self.__dao.checkin(user_name, user_pass)
        if 0 == ret['retcode']:
            ret['retbody']['code'] = base64.standard_b64encode('%s:%s' % (user_name, user_pass,))
        return ret

    def freeze(self, user_id):
        return self.__dao.freeze(user_id)

    def thaw(self, user_id):
        return self.__dao.thaw(user_id)

    def get_userinfo_by_id(self, user_id):
        return self.__dao.get_userinfo_by_id(user_id)
    def get_userinfo_by_name(self, user_name):
        return self.__dao.get_userinfo_by_name(user_name)

    def bonus4checkin(self, user_id):
        inc = self.__bonus_checkin
        key = 'bonus:checkin:%u:%s' % (user_id, time.strftime("%Y%m%H"), )
        md5str = hashlib.md5(key).hexdigest()
        mckey = md5str[:16]
        if not self.__mc.get(mckey):
            # 24小时之内只能奖励一次
            self.__mc.add(mckey, int(time.time()), self.__mc_expire_time)
            return self.__dao.add_activity(user_id, inc)
        else:
            ret = {}
            ret['retcode'] = E_DUP_OPERATION
            ret['message'] = 'checkin twice or more in today user_id[%u].' % (user_id,),
            return ret

    def bonus4ding(self, user_id):
        inc = self.__bonus_ding
        return self.__dao.add_activity(user_id, inc)

    def bonus4post_thread(self, user_id):
        inc = self.__bonus_post_thread
        return self.__dao.add_activity(user_id, inc)

    def bonus4post_comment(self, user_id):
        inc = self.__bonus_post_comment
        return self.__dao.add_activity(user_id, inc)

    def bonus4post_jiong(self, user_id):
        inc = self.__bonus_post_jiong
        return self.__dao.add_activity(user_id, inc)

    def bonus4post_give_me_five(self, user_id):
        inc = self.__bonus_give_me_five
        return self.__dao.add_activity(user_id, inc)

    def bonus4dinged(self, user_id):
        inc = self.__bonus_dinged
        return self.__dao.add_popularity(user_id, inc)

    def bonus4selected(self, user_id):
        inc = self.__bonus_selected
        return self.__dao.add_popularity(user_id, inc)
